package com.wang.code.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.wang.code.dao.JijinRepository;
import com.wang.code.dao.LsjzRepository;
import com.wang.code.dao.UpdateLogRepository;
import com.wang.code.entity.JijinDO;
import com.wang.code.entity.LsjzDO;
import com.wang.code.entity.UpdateLogDO;
import com.wang.entity.JijinVO;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author wanglei
 * @Date 2019/11/27 15:51
 * @Version V1.0
 **/
@Slf4j
@Service
public class JIJinService {

    @Autowired
    private LsjzRepository lsjzRepository;
    @Autowired
    private UpdateLogRepository updateLogRepository;
    @Autowired
    private JijinRepository jijinRepository;


    /**
     * 添加自选基金
     */
    public JijinVO save(String code) {
        code = code.trim();
        JijinDO param = new JijinDO();
        param.setCode(code);
        List<JijinDO> all = jijinRepository.findAll(Example.of(param));
        if (all != null && all.size() > 0) {
            return null;
        }

        String url = StrUtil.format("http://fundgz.1234567.com.cn/js/{}.js", code);
        String body = HttpUtil.get(url);

        String substring = body.substring(body.indexOf("(") + 1, body.indexOf(")"));
        JijinVO jijinVO = JSONObject.parseObject(substring, JijinVO.class);
        JijinDO jijinDO = new JijinDO();
        jijinDO.setCode(jijinVO.getFundcode());
        jijinDO.setName(jijinVO.getName());

        jijinRepository.save(jijinDO);

        String finalCode = code;
        Thread t = new Thread(() -> {
            reptileLSJZ(finalCode, 1);
        });
        t.start();

        return jijinVO;
    }


    /**
     * 爬取历史净值
     */
    public void reptileLSJZ(String code, Integer page) {
        String url = "http://fund.eastmoney.com/f10/F10DataApi.aspx?";
        Map<String, Object> map = new HashMap<>();
        map.put("type", "lsjz");
        map.put("per", "49");
        map.put("code", code);
        map.put("page", page);

        String params = HttpUtil.toParams(map);
        Document dom = null;
        try {
            dom = Jsoup.connect(url + params).get();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Elements trlist = dom.body().select("tbody").select("tr");
        for (Element element : trlist) {
            LsjzDO lsjzDO = new LsjzDO();
            lsjzDO.setCode(code);
            lsjzDO.setDate(element.select("td").get(0).html());
            lsjzDO.setDwjz(new BigDecimal(element.select("td").get(1).html()));
            lsjzRepository.save(lsjzDO);
        }

        log.info("爬取 {} 第 {} 页成功", code, page);
        page++;
        if (trlist.size() == 49) {
            reptileLSJZ(code, page);
        } else {
            UpdateLogDO logDO = new UpdateLogDO();
            logDO.setCode(code);
            logDO.setLastDate(LocalDate.now().plusDays(-1).toString());
            updateLogRepository.save(logDO);
        }
    }

    /**
     * 获取最新净值
     */
    public JijinVO newData(String code) {
        long millis = System.currentTimeMillis();
        String url = "http://fundgz.1234567.com.cn/js/" + code + ".js?rt=" + millis;
        String body = HttpUtil.get(url);

        if (body.length() < 15) {
            return null;
        }
        String substring = body.substring(body.indexOf("(") + 1, body.indexOf(")"));
        return JSONObject.parseObject(substring, JijinVO.class);
    }


}
